// Copyright 2006 - Ricardo Stuven (rstuven@gmail.com)
//
// This file is part of MsSqlSpatial.
// MsSqlSpatial is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// MsSqlSpatial is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public License
// along with MsSqlSpatial; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 

using System;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Server;
using MsSqlSpatial;

public partial class Triggers
{
	[SqlTrigger(Name = "ST_DropGeometryColumn", Target = "DATABASE", Event = "FOR ALTER_TABLE")]
	public static void DropGeometryColumn()
	{
		XmlDocument eventData = new XmlDocument();
		eventData.Load(SqlContext.TriggerContext.EventData.CreateReader());
		string schemaName = eventData.SelectSingleNode("/EVENT_INSTANCE/SchemaName").InnerText;
		string tableName = eventData.SelectSingleNode("/EVENT_INSTANCE/ObjectName").InnerText;
		string commandText = eventData.SelectSingleNode("/EVENT_INSTANCE/TSQLCommand/CommandText").InnerText;

		// RegexOptions.IgnoreCase will not be enough...
		commandText = Regex.Replace(commandText, "[\r\n]", string.Empty);

		Match columnsMatch = Regex.Match(commandText, @"\bDROP\s+COLUMN\s+[""\[]?(.+)[""\]]?", RegexOptions.IgnoreCase);
		if (columnsMatch.Success)
		{
			using (SqlConnection connection = DatabaseHelper.Connection)
			{
				connection.Open();
				using (SqlCommand command = connection.CreateCommand())
				{
					string[] columnNames = Regex.Split(columnsMatch.Groups[1].Value.TrimEnd('"', ']', ' ', ';'), @"[""\]]?\s*,\s*[""\[]?");
					foreach (string columnName in columnNames)
					{
						if (GeometryColumnsTable.CheckGeometryColumnExists(command, schemaName, tableName, columnName))
						{
							GeometryTable.ExecuteDropColumnDependantObjects(command, schemaName, tableName, columnName);

							//SqlContext.Pipe.Send(string.Format(
							//    @"Geometry column [{0}].[{1}].[{2}] dropped."
							//    , schemaName, tableName, columnName));
						}
					}
				}
			}

		}
	}
}
